package top.huhuiyu.springboot2.study.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import top.huhuiyu.springboot2.study.config.MxnzpConfig;
import top.huhuiyu.springboot2.study.entity.joke.NewsDetail;
import top.huhuiyu.springboot2.study.entity.joke.NewsList;
import top.huhuiyu.springboot2.study.entity.joke.NewsType;
import top.huhuiyu.springboot2.study.entity.joke.TbNewsApiInfo;
import top.huhuiyu.springboot2.study.mapper.joke.TbNewsApiInfoMapper;
import top.huhuiyu.springboot2.study.service.NewsApiService;
import top.huhuiyu.springboot2.study.util.JsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 胡辉煜
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class NewsApiServiceImpl implements NewsApiService {
  private final RestTemplate restTemplate;
  private final TbNewsApiInfoMapper tbNewsApiInfoMapper;

  /**
   * 让当前线程停止执行time指定的秒数
   *
   * @param time 线程停止的秒数
   */
  private void sleep(int time) {
    try {
      Thread.sleep(time * 1000L);
    } catch (Exception ex) {
      log.debug("线程休眠异常{}", ex.getMessage());
    }
  }

  private void sleepTwoSeconds() {
    sleep(2);
  }

  @Override
  public NewsType getNewsType() {
    sleepTwoSeconds();
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APP_ID);
    headers.add("app_secret", MxnzpConfig.APP_SECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    String url = MxnzpConfig.NEWS_TYPE_URL;
    String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
    log.debug("新闻分类：{}", result);
    return JsonUtils.parse(result, NewsType.class);
  }

  @Override
  public List<NewsList> getNewsList(NewsType newsType) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APP_ID);
    headers.add("app_secret", MxnzpConfig.APP_SECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    List<NewsList> list = new ArrayList<>();
    newsType.getData().forEach(type -> {
      sleepTwoSeconds();
      String url = String.format(MxnzpConfig.NEWS_LIST_URL, type.getTypeId(), 1);
      log.debug("url:{}", url);
      String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
      log.debug("新闻列表：{}", result);
      list.add(JsonUtils.parse(result, NewsList.class));
    });
    return list;
  }

  @Override
  public List<NewsDetail> getNewsDetail(List<NewsList> list) {
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APP_ID);
    headers.add("app_secret", MxnzpConfig.APP_SECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    List<NewsDetail> detailList = new ArrayList<>();
    for (NewsList newsList : list) {
      // 只查询第一笔记录
      NewsList.NewsListData data = newsList.getData().get(0);
      sleepTwoSeconds();
      String url = String.format(MxnzpConfig.NEWS_INFO_URL, data.getNewsId());
      String result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
      log.debug("新闻详情：{}", result);
      detailList.add(JsonUtils.parse(result, NewsDetail.class));
    }
    return detailList;
  }

  @Override
  public int saveNews() {
    final int[] count = new int[]{0};
    // 请求的基本信息=================================================
    HttpHeaders headers = new HttpHeaders();
    headers.add("app_id", MxnzpConfig.APP_ID);
    headers.add("app_secret", MxnzpConfig.APP_SECRET);
    HttpEntity<String> entity = new HttpEntity<>("", headers);
    // 第一步，获取新闻分类=============================================
    String result = restTemplate.exchange(MxnzpConfig.NEWS_TYPE_URL, HttpMethod.GET, entity, String.class).getBody();
    log.debug("新闻分类：{}", result);
    NewsType newsType = JsonUtils.parse(result, NewsType.class);
    // 第二步，获取新闻列表=============================================
    newsType.getData().forEach(type -> {
      sleepTwoSeconds();
      String url = String.format(MxnzpConfig.NEWS_LIST_URL, type.getTypeId(), 1);
      String listResult = restTemplate.exchange(url, HttpMethod.GET, entity, String.class).getBody();
      log.debug("新闻列表：{}", listResult);
      NewsList newsList = JsonUtils.parse(listResult, NewsList.class);
      // 第三步，获取新闻详情=============================================
      newsList.getData().forEach(data -> {
        sleepTwoSeconds();
        String detailUrl = String.format(MxnzpConfig.NEWS_INFO_URL, data.getNewsId());
        String detailResult = restTemplate.exchange(detailUrl, HttpMethod.GET, entity, String.class).getBody();
        log.debug("新闻详情：{}", detailResult);
        // 第四步，组织新闻详情=============================================
        NewsDetail newsDetail = JsonUtils.parse(detailResult, NewsDetail.class);
        TbNewsApiInfo tbNewsApiInfo = new TbNewsApiInfo();
        tbNewsApiInfo.setNewsId(data.getNewsId());
        tbNewsApiInfo.setDigest(data.getDigest());
        tbNewsApiInfo.setSource(data.getSource());
        tbNewsApiInfo.setTitle(data.getTitle());
        tbNewsApiInfo.setTypeName(type.getTypeName());
        tbNewsApiInfo.setPostTime(data.getPostTime());
        // 获取新闻内容
        StringBuilder sb = new StringBuilder();
        newsDetail.getData().getItems().forEach(item -> {
          if ("text".equalsIgnoreCase(item.getType())) {
            sb.append(String.format("<p>%s</p>", item.getContent()));
          } else if ("img".equalsIgnoreCase(item.getType())) {
            sb.append(String.format("<img src='%s'>", item.getImageUrl()));
          }
        });
        tbNewsApiInfo.setContent(sb.toString());
        // 第五步，添加到数据库
        tbNewsApiInfoMapper.insert(tbNewsApiInfo);
        count[0]++;
      });
    });
    return count[0];
  }


}
